import logging

from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request

from flask import session

from info import redis_store
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route("/")
@user_login_data
def index():
    # redis_store.set("name","python")
    # session["age"] = 20
    # print(session.get("age"))
    # logging.debug("这是debug内容")
    # logging.info("这是info内容")
    # logging.warning("这是warning内容")
    # logging.error("这是error内容")
    # 获取到当前登录用户的id
    user = g.user

    try:
        from info import constants
        news_click = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    data = {
        "user": user.to_dict() if user else None,
        "news_click": news_click,
        "categories" :categories
    }
    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def get_web_icon():
    return current_app.send_static_file("news/favicon.ico")

# 1、获取参数，前端发送通过GET参数发送
# 2、分页查询新闻表中的新闻(根据分类id，即cid；降序；使用分页查询；查询到的是python的模型对象列表)
# 3、返回新闻数据


@index_blu.route("/news_list")
def news_list():
    data_dict = request.args
    cid = data_dict.get("cid")
    page = data_dict.get("page")
    per_page = data_dict.get("per_page")
    try:
        page = int(page)
        per_page = int(per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        filters = [News.status==0]
        if cid != 1:
            filters.append(News.category_id == cid)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page)
        items = paginate.items
        currentPage = paginate.page
        totalPage = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    newsList = []
    for news in items:
        newsList.append(news.to_basic_dict())
    return jsonify(errno=RET.OK,errmsg="查询成功",newsList=newsList,currentPage=currentPage,totalPage=totalPage)
